import tkinter as tk, os
from tkinter import messagebox

import strange_io as func, editor

class MainApplication(tk.Tk):
    def __init__(self, cmd_args, app_config, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.title("Strange Pixels Editor - Strange I/O")
        self.minsize(300, 200)

        self.grid_rowconfigure(0, weight=1)  # Make the first row expandable
        self.grid_columnconfigure(0, weight=1)  # Make the first column expandable

        self.container = tk.Frame(self)
        self.container.grid(row=0, column=0, sticky="nsew")
        self.container.grid_rowconfigure(0, weight=1)  # Make the first row of container expandable
        self.container.grid_columnconfigure(0, weight=1)  # Make the first column of container expandable

        self.gui_frames = {}

        self.add_gui(editor.PixelsEditor, app_config,
                cmd_args.width if cmd_args.width else app_config['canvas']['geometry']['width'],
                cmd_args.height if cmd_args.height else app_config['canvas']['geometry']['height'],
                cmd_args.size if cmd_args.size else app_config['canvas']['pixel']['size']
            )

        pixels = editor.PixelsEditor.__name__
        if cmd_args.palette:
            self.gui_frames[pixels].current_palette_file.set(cmd_args.palette)
            self.gui_frames[pixels].colors.load_file(cmd_args.palette)
            self.gui_frames[pixels].refresh_color_menu()
            self.gui_frames[pixels].refresh_canvas()

        if cmd_args.file_path:
            if os.path.exists(cmd_args.file_path):
                if os.path.isfile(cmd_args.file_path):
                    try:
                        _format = func.get_format(cmd_args.file_path)
                        if _format == b'pixels':
                            gui_class = editor.PixelsEditor
                            gui_name = gui_class.__name__
                            gui_object = self.gui_frames[gui_name]
                            gui_object._open_file(cmd_args.file_path)
                        self.show_gui(editor.PixelsEditor)
                    except ValueError:
                        print(f'\'{cmd_args.file_path}\' isn\'t a Strange I/O Document')
                else:
                    print(f'\'{cmd_args.file_path}\' isn\'t a file')
            else:
                print(f'\'{cmd_args.file_path}\' doesn\'t exist')

        self.protocol("WM_DELETE_WINDOW", self.on_closing)

    def add_gui(self, gui_class, *args):
        gui_name = gui_class.__name__
        self.gui_frames[gui_name] = gui_class(self.container, self, *args)

    def show_gui(self, gui_class):
        gui_name = gui_class.__name__
        frame = self.gui_frames[gui_name]
        self.config(menu=frame.menu_bar)
        frame.grid(row=0, column=0, sticky="nsew")
        frame.tkraise()

    def on_closing(self):
        exit = False
        if self.gui_frames[editor.PixelsEditor.__name__].is_edited.get():
            if messagebox.askokcancel('Unsaved Change Buffer', 'You have unsaved changes in the change buffer, are you sure you want to exit?'):
                exit = True
        else:
            exit = True
        if exit:
            self.quit()
            print("Good by!")
